package com.xyd.servlet;

import com.xyd.entity.Comment;
import com.xyd.entity.Message;
import com.xyd.entity.User;
import com.xyd.service.CommentService;
import com.xyd.service.impl.CommentServiceImpl;
import com.xyd.util.JsonUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：发表留言
 *
 * @author 张吉哲
 * @date 2021/1/9 16:33
 */
@WebServlet("/commentAddServlet")
public class CommentAddServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Message message = new Message();
    User user = (User) request.getSession().getAttribute("user");
    if (user == null) {
      message.setFlag(false);
      message.setMessage("您尚未登录，请登录");
      JsonUtil.toJson(response, message);
      return;
    }

    String guestContent = request.getParameter("guestContent");
    Comment comment = new Comment();
    comment.setEcContent(guestContent);
    comment.setEcNickName(user.getEuUsername());
    CommentService commentService = new CommentServiceImpl();
    Boolean flag = commentService.addComment(comment);
    message.setFlag(flag);
    if (flag) {
      message.setMessage("回复成功");
    } else {
      message.setMessage("提交失败，请联系管理员");
    }

    JsonUtil.toJson(response, message);
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request, response);
  }
}
